class PlaylistItem < ActiveRecord::Base
  #Relations:
  belongs_to :song
  belongs_to :playlist
  
  #Plugins:
  acts_as_list :scope => :playlist
  
  #Validations:
  validates_uniqueness_of :song_id, :scope => :played_at
  #validates_uniqueness_of :playing, :if => self.playing == true
  validates_uniqueness_of :playing, :if => Proc.new { |pi| pi.playing == true }
  
  #Callbacks/filters:
  before_create :add_to_radio_playlist
  after_destroy :remove_from_radio_playlist
  #before_update :update_radio_playlist_position #Hoeft niet: dit moet doer een nieuwe vote gedaan worden!
  after_save 'Jukebox.if_not_playing_make_it_so'
  before_save Proc.new { |pi| pi.played_at = DateTime.now if pi.playing == true }
  
  #methods:
  def add_to_radio_playlist
    Jukebox.radio.add(self.song.file)
  end
  
  def remove_from_radio_playlist
    Jukebox.radio.delete(self.mpd_position) if Jukebox.radio.playlist[self.mpd_position]
  end
  
  def mpd_song
    Jukebox.radio.playlist.select { |song| song.file == self.song.file }[0]
  end
  
  #The mpd position is the self.position
  def mpd_position
    return self.mpd_song.pos.to_i
  end
  
  def mark_as_current_song
    self.playing = true
    self.played_at = DateTime.now
    self.move_to_top
  end
  
  def mark_as_played
    self.playing = false
    self.remove_from_list #make position nil!
    self.save
    
    #Also remove from radio
    Jukebox.playlist.sync_with_radio
  end
  
  def played?
    return played_at
  end
  
end